import { ref, computed, onMounted } from "vue";
import { getBills, deleteBill as deleteBillAPI, ApiBill } from "../../api/modules/bill.api";

export interface Bill {
    date: string;
    amount: number;
    category: string;
    remark: string;
    id: number;
}

export function useBillListPage() {
    // 账单分类列表（与AddPage保持一致）
    const categories = ref([
        { name: "餐饮", icon: "🍕" },
        { name: "交通", icon: "🚆" },
        { name: "购物", icon: "🛒" },
        { name: "生活缴费", icon: "💡" },
    ]);

    // 内部使用的账单列表数据
    const bills = ref<Bill[]>([]);
    // 当前选中的日期（格式："YYYY-MM-DD"）
    const selectedDate = ref<string | null>(null);
    // BillListPage.ts 中添加 isLoading 状态
    const isLoading = ref(false);
    // 当前查询的年月
    const currentYear = ref(new Date().getFullYear());
    const currentMonth = ref(new Date().getMonth() + 1);


    // 从后端获取账单数据（支持按月查询）
    const fetchBills = async (year?: number, month?: number) => {
        try {
            const result = await getBills(0, 1000, year, month);
            // 转换接口数据结构
            bills.value = result.map((item: ApiBill) => ({
                date: item.bill_date,
                amount: item.amount,
                category: item.category,
                remark: item.remark,
                id: item.id,
            }));
        } catch (error) {
            console.error("获取账单数据失败：", error);
        }
    };

    // 监听月份变化
    const handleMonthChanged = (date: { year: number; month: number }) => {
        currentYear.value = date.year;
        currentMonth.value = date.month;
        fetchBills(date.year, date.month);
    };

    // 组件挂载后请求当前月份数据
    onMounted(() => {
        fetchBills(currentYear.value, currentMonth.value);
    });

    // 计算每日账单总额
    const dailyTotals = computed(() => {
        const totals: Record<string, number> = {};
        bills.value.forEach((bill) => {
            if (!totals[bill.date]) {
                totals[bill.date] = 0;
            }
            totals[bill.date] += bill.amount;
        });
        return totals;
    });

    // 格式化日期单元格数据
    const formatter = (day: any) => {
        if (!day.date) return day;
        const year = day.date.getFullYear();
        const month = (day.date.getMonth() + 1).toString().padStart(2, "0");
        const date = day.date.getDate().toString().padStart(2, "0");
        const dateStr = `${year}-${month}-${date}`;
        if (dailyTotals.value[dateStr] !== undefined) {
            day.topInfo = dailyTotals.value[dateStr];
        }
        return day;
    };

    // 日历选中事件
    const handleDaySelected = (dateObj: Date) => {
        const year = dateObj.getFullYear();
        const month = (dateObj.getMonth() + 1).toString().padStart(2, "0");
        const date = dateObj.getDate().toString().padStart(2, "0");
        selectedDate.value = `${year}-${month}-${date}`;
    };

    // 根据选中的日期过滤账单
    const filteredBills = computed(() => {
        if (!selectedDate.value) return [];
        return bills.value.filter(bill => bill.date === selectedDate.value);
    });

    // 计算选中日期下账单总金额
    const totalForSelected = computed(() => {
        return filteredBills.value.reduce((sum, bill) => sum + bill.amount, 0);
    });

    // 根据账单类别返回图标
    const getIcon = (category: string) => {
        const icons: Record<string, string> = {
            "餐饮": "🍕",
            "交通": "🚆",
            "购物": "🛒",
            "生活缴费": "💡",
        };
        return icons[category] || "📊";
    };

    const deleteBill = async (billId: number) => {
        isLoading.value = true;
        try {
            await deleteBillAPI(billId);
            // 删除成功后，从本地账单数据中移除该项
            bills.value = bills.value.filter(b => b.id !== billId);
        } catch (error) {
            console.error("删除账单失败：", error);
        } finally {
            isLoading.value = false;
        }
    };

    return {
        bills,
        categories, // 类别列表
        formatter,
        selectedDate,
        handleDaySelected,
        filteredBills,
        totalForSelected,
        getIcon,
        fetchBills, // 如果需要重新请求，可以调用此方法
        deleteBill,  // 新增删除方法
        isLoading, // 添加这一行
        handleMonthChanged, // 月份变化处理函数
        currentYear, // 当前年份
        currentMonth, // 当前月份
    };
}